var param = {}, formId = 'queryForm', url = "/posting/promotionActivityService/list";
let days = 30;
let rowindex = 100;
let topChannelCodeList = [];
let channelMap = new Map();
//点击查询按钮调用
$.openx.query = function () {
    try {
        getSystemParam();
    } catch (e) {
        console.info(e)
    }
    let activityStartTime = new Date($("#queryActivityStartTime").val().replace(/\-/g, "\/"));
    let activityEndTime = new Date($("#queryActivityEndTime").val().replace(/\-/g, "\/"));
    getDaysByMonth(activityStartTime.getFullYear(), activityStartTime.getMonth() + 1);
    if (activityStartTime > activityEndTime) {
        layer.msg('活动开始时间不能大于活动结束时间！');
        return false;
    }
    let data = $.openx.getJsonObj(formId);
    param.queryForm = {
        topChannelCode: data.queryTopChannelCode,
        activityType: data.activityType,
        ActivityName: data.activityName,
        activityStatus: data.activityStatus,
        activityStartTime: data.activityStartTime,
        activityEndTime: data.activityEndTime,
    };
    console.log('param', data)
    var equryTimeStamp = new Date();
    tableRefresh(url + "?t=" + equryTimeStamp.getTime(), param);
    $('#table').bootstrapTable({pageList: [10, 25, 50]});
}

function tableRefresh(url, data, refresh) {
    if (url && data) $($.openx.tableId).bootstrapTable('refresh', {url: jot_posting_server + url, query: data});
    if (refresh) $("button[name ='refresh'][type='button']").click();
    $.openx.rows = [];
}

//启用
function enable(row) {
    ajax(jot_posting_server + "/posting/promotionActivityService", "enable").callx({
        id: row.id,
        onResult: function (result) {
            $.openx.query();
        },
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}

//禁用
function disable(row) {
    ajax(jot_posting_server + "/posting/promotionActivityService", "disable").callx({
        id: row.id,
        onResult: function (result) {
            $.openx.query();
        },
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}

let activity = {}
function changeGoodsCode(el, parentNode) {
    ajax(ecp_boss_server + "/goods/goodsServer", "queryDetail").callx({
        goodsCode: $(el).val(),
        onResult: function (result) {
            if (!result) {
                layer.msg('商品不存在');
            } else {
                let td = $(parentNode).find("td");
                td.eq(1).text(result.goodsName);
            }
        }
        ,
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}

//确认列数据
function addRowsData(curr, tr) {
    rowindex = parseInt($(tr).attr("data-index")) + rowindex;
    let cloneTr = $(tr).clone(true);
    let td = cloneTr.find("td");
    $(td).eq(0).find("input[name='goodsCodeValue']")[0].setAttribute('value', '');
    $(td).eq(1).text('')
    let newRow = "<tr data-index=" + rowindex + ">" + cloneTr.html() + "</tr>";
    $(tr).after(newRow);
    let deleteButton = $(tr).next().find("td").eq(7).find("button").eq(1);
    deleteButton.removeAttr("disabled");
    deleteButton.attr("class", "btn btn-outline btn-danger btn-xs")
}

function getGoodsTableData(id) {
    let array = [];
    $("#" + id).find("tbody tr").each(
        function (i, item) {
            let goods = {};
            /**当前行批号*/
            let td = $(item).find("td");
            /**商品编码*/
            goods.goodsCode = $(td).eq(0).find("input[name='goodsCodeValue']")[0] ? $(td).eq(0).find("input[name='goodsCodeValue']")[0].value : '';
            /**商品数量*/
            goods.quantity = $(td).eq(2).find("input[name='quantityValue']")[0] ? $(td).eq(2).find("input[name='quantityValue']")[0].value : '';
            array.push(goods);
        });
    return array;
}

//删除列数据
function deleteRowsData(id, tr) {
    let array = getGoodsTableData(id);
    if (array.length <= 1) {
        layer.msg("至少保留一个商品");
        return;
    }
    $(tr).remove();
}

function checkParam(param) {
    if (!param) {
        return false;
    }
    if (!param.activityName) {
        layer.tips('请输入活动名称', '#activity_name_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (strLength(param.activityName) > 30) {
        layer.tips('活动名称不能超过30个字', '#activity_name_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (!param.topChannelCode) {
        layer.tips('请选择顶级渠道', '#top_channel_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }

    if (param.activityChannels <= 0) {
        layer.tips('请选择子渠道', '#channel_code_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (!param.promotionCode) {
        layer.tips('请输入方案编码', '#promotion_code_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (strLength(param.promotionCode) > 30) {
        layer.tips('方案编码不能超过30个字', '#promotion_code_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (!param.activityType) {
        layer.tips('请选择活动类型', '#activity_type_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (!param.activityStartTime) {
        layer.tips('请选择活动开始时间', '#activity_start_time_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (!param.activityEndTime) {
        layer.tips('请选择活动结束时间', '#activity_end_time_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (param.activityStartTime > param.activityEndTime) {
        layer.tips('开始时间不能大于结束时间', '#activity_end_time_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    if (param.activityGoods.length <= 0) {
        layer.tips('请选择商品', '#goods_list_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    let pass = true;
    param.activityGoods.forEach(item => {
        if (!pass) {
            return;
        }
        if (!item.goodsCode) {
            layer.msg("商品为空");
            pass = false;
        }
        if (!item.quantity) {
            layer.msg("条件数量为空");
            pass = false;
        }
        let re = /^\+?[1-9]\d*$/;
        if (!re.test(item.quantity)) {
            layer.msg("条件数量不是正整数");
            pass = false;
        }
        item.quantity = parseInt(item.quantity);
    });
    return pass;
}

//字符长度
function strLength(str) {
    let len = 0;
    if (!str) {
        return len;
    }
    for (let i = 0; i < str.length; i++) {
        let c = str.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            len++;
        } else {
            len += 2;
        }
    }
    return len;
}

//修改
function edit(row) {
    ajax(jot_posting_server + "/posting/promotionActivityService", "get").callx({
        id: row.id,
        onResult: function (data) {
            activity = data;
            let result = {
                id: data.id,
                activityName: data.activityName,
                topChannelCode: data.topChannelCode,
                promotionCode: data.promotionCode,
                activityType: data.activityType,
                activityStartTime: data.activityStartTime,
                activityEndTime: data.activityEndTime,
                accumulation: data.accumulation,
            };
            let goodsList = [];
            let giftGoodsList = [];
            if (data.activityGoods && data.activityGoods.length > 0) {
                data.activityGoods.forEach(item => {
                    if (item.gift === 'Y') {
                        giftGoodsList.push({
                            goodsCode: item.goodsCode,
                            quantity: item.quantity,
                            goodsName: item.goodsName
                        })
                    }
                    if (item.gift === 'N') {
                        goodsList.push({goodsCode: item.goodsCode, quantity: item.quantity, goodsName: item.goodsName})
                    }
                });
                result.goodsList = goodsList;
                result.giftGoodsList = giftGoodsList;
            } else {
                result.goodsList = [{goodsCode: '', quantity: 1}]
                result.giftGoodsList = [{goodsCode: '', quantity: 1}]
            }
            let channels = [];
            data.activityChannels.forEach(item => {
                channels.push(item.channelCode);
            });
            initTopChannel("topChannelCode");
            let createForm = "savePromotionActivityForm";
            let innerHtml = $.openx.innerHtml('savePromotionActivityDialog');
            laytpl(innerHtml).render(result, function (html) {
                $.openx.openLayer(['900', '800'], '修改满赠活动', html, false, function () {
                    //表单提交移除禁用
                    $("#promotionCode").removeAttr("disabled");
                    $("#activityType").removeAttr("disabled");
                    $("#topChannelCode").removeAttr("disabled");
                    let param = $.openx.getJsonObj(createForm);
                    let data = this.buildParam(param);
                    let pass = checkParam(data);
                    if (pass) {
                        data.id = activity.id;
                        update(data);
                    }
                });
            });
            //修改禁用
            $("#promotionCode").attr("disabled", true);
            $("#activityType").attr("disabled", true);
            $("#topChannelCode").attr("disabled", true);
            $('#activityType').val(result.activityType);
            document.getElementById('activityStartTime').value = $.openx.formatDate(new Date(result.activityStartTime), "yyyy-MM-dd hh:mm:ss");
            document.getElementById('activityEndTime').value = $.openx.formatDate(new Date(result.activityEndTime), "yyyy-MM-dd hh:mm:ss");
            setTimeout(function () {
                $('#topChannelCode').val(result.topChannelCode);
                changeToChannelCode(row.topChannelCode, channels);
                document.getElementById('channelCode').value = data.activityChannels.length + "个选中项"
            }, 1000);
        }
        ,
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}


//新增
$.openx.insert = function () {
    let result = {
        activityName: '',
        goodsList: [
            {
                goodsCode: '',
                quantity: 1
            }
        ],
        giftGoodsList: [
            {
                goodsCode: '',
                quantity: 1
            }
        ],
        accumulation: 'N',

    }
    initTopChannel("topChannelCode");
    let createForm = "savePromotionActivityForm";
    let innerHtml = $.openx.innerHtml('savePromotionActivityDialog');
    laytpl(innerHtml).render(result, function (html) {
        $.openx.openLayer(['900', '800'], '新增满赠活动', html, false, function () {
            let param = $.openx.getJsonObj(createForm);
            let data = this.buildParam(param);
            let pass = checkParam(data);
            if (pass) {
                save(data);
            }
        });
    });
}

function buildParam(param) {
    if (!param.topChannelCode) {
        layer.tips('请选择顶级渠道', '#top_channel_tips', {
            tips: [2, '#ff4400']
        });
        return false;
    }
    let data = {
        topChannelCode: param.topChannelCode,
        activityName: param.activityName,
        promotionCode: param.promotionCode,
        activityType: param.activityType,
        activityStartTime: param.activityStartTime,
        activityEndTime: param.activityEndTime,
        accumulation: param.isDefault === 'true' ? 'Y' : 'N',
    };
    let goodsList = getGoodsTableData(param.goodsList);
    let giftGoodsList = getGoodsTableData(param.giftGoodsList);
    let activityGoods = [];
    goodsList.forEach(item => {
        activityGoods.push({
            goodsCode: item.goodsCode,
            quantity: item.quantity,
            gift: 'N'
        })
    });
    giftGoodsList.forEach(item => {
        activityGoods.push({
            goodsCode: item.goodsCode,
            quantity: item.quantity,
            gift: 'Y'
        })
    });
    data.activityGoods = activityGoods;
    let channels = $("#channelCode").yfChannel("getData");
    let activityChannels = [];
    if (channels.length > 0) {
        channels.forEach(item => {
            activityChannels.push({
                channelCode: item.displayChannel
            });
        })
    };
    data.activityChannels = activityChannels;
    return data;
}

function save(param) {
    ajax(jot_posting_server + "/posting/promotionActivityService", "save").callx({
        promotionActivity: param,
        onResult: function (result) {
            layer.msg('操作成功');
            tableRefresh(null, null, true);
            layer.closeAll();
        }
        ,
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}

function update(param) {
    ajax(jot_posting_server + "/posting/promotionActivityService", "update").callx({
        promotionActivity: param,
        onResult: function (result) {
            layer.msg('操作成功');
            tableRefresh(null, null, true);
            layer.closeAll();
        }
        ,
        onError: function (error) {
            layer.msg(error.msg);
        }
    });
}

//顶级渠道变更
async function changeToChannelCode(topChannelCode, channels) {
    if (!topChannelCode) {
        layer.msg("请选择顶级渠道");
        return;
    }
    $("#channelCode").attr("disabled", false);
    if(channels && channels.length > 0){
        $("#channelCode").yfChannel("reset");
    }
    let options = {
        service: '/boss/channelService',
        method: "/listChannelTree",
        refreshMethod: "refreshChannelTree",
        importMethod: "importChannelCode",
        filter: 'leaves',
        topChannelCode: topChannelCode,
        checkChannels: channels,
        isSearch: true,
        isImport: true,
    };
    $("#channelCode").yfChannel(options);
}


function resetForm() {
    $('#queryForm')[0].reset();
    let laydate = layui.laydate;
    document.getElementById('queryActivityStartTime').value = laydate.now(-1).split(' ')[0] + ' 00:00:00';
    document.getElementById('queryActivityEndTime').value = laydate.now().split(' ')[0] + ' 23:59:59';
    let data = $.openx.getJsonObj(formId);
    initTable("table", url, param);
    $.openx.query();
}

//初始化日期控件时间
layui.use('laydate', function () {
    let laydate = layui.laydate;
    document.getElementById('queryActivityStartTime').value = laydate.now(-1) + ' 00:00:00';
    document.getElementById('queryActivityEndTime').value = laydate.now() + ' 23:59:59';
    let data = $.openx.getJsonObj(formId);
    param.queryForm = data;
    initTopChannel("queryTopChannelCode");
    setTimeout(function () {
        initTable("table", url, param, null, [10, 25, 50]);
    }, 500);
});

/**
 * 格式化下单时间
 */
function createTimeFormat(value, row) {
    return $.openx.formatDate(new Date(value), "yyyy-MM-dd hh:mm");
}

function topChannelFormat(value, row) {
    return channelMap.get(value);
}

function activityType(value, row) {
    if (value === '3') {
        return '单品买赠';
    }
    return '';
}

function enableFormat(value, row) {
    if ('Y' === value) {
        return '启用';
    }
    if ('N' === value) {
        return '禁用';
    }
    return '';
}

//格式化操作栏按钮
function operationFormat(value, row) {
    let enableHtml = '';
    if (row.enable === 'Y') {
        enableHtml = "<a href=\'javascript:void(0)\' style='color: #0e9aef' onclick =\'javascript:disable(" + JSON.stringify(row) + ")\'>" + '禁用' + "<a>";
    }
    if (row.enable === 'N') {
        enableHtml = "<a href=\'javascript:void(0)\' style='color: #0e9aef' onclick =\'javascript:enable(" + JSON.stringify(row) + ")\'>" + '启用' + "<a>";
    }
    let editHtml = "<a href=\'javascript:void(0)\' style='color: #0e9aef;margin-left: 15px' onclick =\'javascript:edit(" + JSON.stringify(row) + ")\'>修改<a>";
    return enableHtml + editHtml;
}

async function initTopChannel(second) {
    $X("/boss/channelService", "listAllTopChannel").callx({
        onResult: function (data) {
            if (data) {
                $("#" + second).append("<option value='''>" + '请选择' + "</option>");
                topChannelCodeList = data;
                data.forEach(item => {
                    channelMap.put(item.channelCode, item.name);
                    $("#" + second).append("<option value=\"" + item.channelCode + "\">" + item.name + "</option>");
                })
            } else {
                layer.msg("无信息")
            }
        },
        onError: function (error) {
            let res = JSON.parse(error);
            layer.msg(res.message)
        }
    });
}


function getDaysByMonth(year, month) {
    var monthDays;
    //判断月份大小获得天数
    if (month === '1' || month === '3' || month === '5' || month === '7' || month === '8' || month === '10' || month === '12') {
        monthDays = 31;
    } else if (month === '4' || month === '6' || month === '9' || month === '11') {
        monthDays = 30;
    } else {
        monthDays = 28;
        //判断当前选择的年份是否是闰年
        if ((year % 100 === 0 && year % 400 === 0) || year % 4 === 0) {
            monthDays = 29;
        }
    }
    days = monthDays;
    return days;
}

function getSystemParam() {
    ajax(x_jot_sic_server + "/SysParamService", "getSystemParam").callx({
        onResult: function (data) {
            if (data) {
                allowConsortGoBack = data.allowConsortGoBack;
                allowTransferReject = data.allowTransferReject;
            }
        },
        onError: function (error) {
        }
    });
}

/**初始化表格*/
function initTable(tableId, url, params, callback, pageList) {
    //封装分页对象 默认从第一条开始  每页10条
    var request = new Object();
    // 分页参数自定义
    $.openx.tableId = !tableId ? "#table" : "#" + tableId;
    // 定义表格的默认样式
    request.queryParams = function (data) {
        if (!params) {
            return {"_openx_head": getOpenxHeader()}
        }
        var isExport = (!data.offset && !data.limit);
        var page = new Object();
        page.offset = data.offset;
        page.pageNum = isExport ? 1 : (parseInt(parseInt(data.offset) + parseInt(data.limit)) / parseInt(data.limit))
        page.pageSize = isExport ? 5000 : data.limit;
        page.pageSizeZero = isExport;
        page.countSql = !isExport;
        page.isExport = isExport;
        params.page = page;
        params._openx_head = getOpenxHeader();
        return params;
    }

    //如果存在先销毁
    $($.openx.tableId).bootstrapTable('destroy');
    $($.openx.tableId).bootstrapTable({
        url: jot_posting_server + url,
        queryParams: request.queryParams,
        pagination: true,
        align: "center",
        striped: true,
        pageNumber: $.openx.pageNumber,
        pageSize: $.openx.pageSize,
        search: false,
        showToggle: false,
        clickToSelect: true,
        pageList: pageList,
        method: 'post',
        showRefresh: true,
        silent: true,
        sidePagination: 'server',
        showColumns: !0,
        toolbar: "#TableToolbar",
        iconSize: "outline",
        icons: {
            toggle: "glyphicon-list-alt",
            columns: "glyphicon-list",
            refresh: "glyphicon-refresh icon-refresh"

        },
        onPageChange: function (num, size) {
            $.openx.pageNumber = num;
            $.openx.pageSize = size;
            $.openx.rows = [];
        },
        responseHandler: function (res) {
            if (callback) {
                callback(res);
            }
            return res;
        },
        onCheck: function (row) {
            $.openx.rows.push(row);
        },
        onUncheck: function (row) {
            for (var i = 0; i < $.openx.rows.length; i++) {
                if ($.openx.rows[i] === row) {
                    $.openx.rows.splice(i, 1);
                }
            }
        },
        onCheckAll: function (rows) {
            $.openx.rows = rows;
        },
        onUncheckAll: function (rows) {
            $.openx.rows = [];
        }
    });

    $($.openx.tableId).on('click-row.bs.table', function (e, row, $element) {
        // 设置表格选择后的颜色
        $('.success').removeClass('success');
        $($element).addClass('success');
    });

    // 对应事件 onLoadSuccess
    $($.openx.tableId).on('load-success.bs.table', function (e, row, $element) {
        layer.closeAll('loading');
    });

    //对应事件 onLoadError
    $($.openx.tableId).on("load-error.bs.table", function (xhr, error) {

        if (error === 500) {
            layer.msg("数据加载失败,服务器出错");
            layer.closeAll('loading');
        } else {
            layer.msg("数据加载失败,服务器出错");
        }
    });
}

function ajax(mapping, method) {
    let _m = mapping;
    let _t = method;
    this.callx = function (data, timeout) {
        let url = _m + '/' + _t;
        if (openx.isNull(data)) {
            data = {};
        }
        openx.invoke(url, openx.conf()['type'], data, timeout, data.onResult, data.onError);
    };
    return this;
}
